# coding=utf8
import re
import traceback
import time

from tools.config import _config
from tools.timing import get_survival


def monitor(logger, name):
    logger.info("主程序已全部启动，剩下开始进行监听。")

    count = 0
    while 1:
        count += 1

        survival = _config("survival_{}".format(name), isint=True, israise=False)
        if survival is not None and survival != 1:
            break

        logger.debug("主程序正常运行，{0}".format(count))
        time.sleep(10)

    logger.info("主程序结束。")


def run(logger, name, func, *args, **kwargs):
    kwargs["logger"] = logger
    yield func(*args, **kwargs)

    time.sleep(5)
    monitor(logger, name)


def main(logger, func, *args, **kwargs):
    name = re.search('(exec.*?)\s+', str(func)).group(1)

    try:
        logger.info(name + "主进程开始执行了。")
        for _ in run(logger, name, func, *args, **kwargs):
            pass
        logger.info(name + "主进程检测到该结束了。")

        while 1:
            if get_survival(name):
                break
            logger.info(name + "主进程检测子进行还未执行完，正在等待。")
            time.sleep(5)

        logger.info(name + "主进程检测执行成功。")
    except Exception as error:
        logger.info(name + "主进程检测执行失败, {}".format(error))
        logger.info(name + str(traceback.format_exc()))
    finally:
        pass

